import { NextRequest, NextResponse } from "next/server";
const crypto = require('crypto');
const querystring = require('querystring');

// 构建签名
function build_msg_signature(encrypt, appid, timeStamp, nonce) {
    const arr = [encrypt, timeStamp, nonce, appid];
    const sorted_string = arr.sort().join('');
    const sha1_hash = crypto.createHash('sha1').update(sorted_string).digest('hex');
    return sha1_hash;
}

// 计算 MD5 值
function get_md5(text) {
    const md5_hash = crypto.createHash('md5').update(text).digest('hex');
    return md5_hash;
}

// AES CBC 模式解密
function aes_cbc_decrypt(app_key, iv, base64_str) {
    // 填充 Base64 字符串
    while (base64_str.length % 4 !== 0) {
        base64_str += '=';
    }
    const decipher = crypto.createDecipheriv('aes-256-cbc', app_key, iv);
    let decrypted = decipher.update(base64_str, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

// 解密
function decrypt(base64_str, app_secret) {
    base64_str = querystring.unescape(base64_str);
    const iv = get_md5(app_secret).slice(0, 16);
    return aes_cbc_decrypt(app_secret, iv, base64_str);
}


export async function POST(req) {

    const body = await req.json();
    const { encrypt, appid, msgSignature, timeStamp, nonce } = body;

    // appid 对应的 appSecret
    const app_secret = process.env.APP_SECRET;

    const my_msg_signature = build_msg_signature(encrypt, appid, timeStamp, nonce);
    const is_ok = my_msg_signature === msgSignature; 
    if (!is_ok) {
        return NextResponse.json({ code: 401, msg: '签名错误' })
    }

    const data_json = decrypt(encrypt, app_secret); 
    return NextResponse.json(
        { code: 200, msg: '解密成功', data: JSON.parse(data_json) },
        { status: 200 }
    );
}

// 下方参数值可从跳转后的 url 中获取
